﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Browser;

namespace ecpuMonitor
{
    public partial class MainPage : UserControl
    {
        public static Analytics _analytics = new Analytics();

        private static ProgressBar _cpuUsageBar;
        private static TextBlock _cpuUsageValue;

        private static double _maxLoad = 25.0;

        private Thread _threadR;

        private static bool _toSendUnpause = false;
        public bool ToSendUnpause
        {
            get { return _toSendUnpause; }
            set { _toSendUnpause = value; }
        }

        public MainPage()
        {
            InitializeComponent();

            HtmlPage.RegisterScriptableObject("ecpuMonitor", this);

            _cpuUsageValue = useCPU_value;
            _cpuUsageBar = useCPU_bar;

            maxUsage_value.Text = _maxLoad.ToString();

            _threadR = new Thread(DoMonitoring);
            _threadR.Start();
        }

        private void DoMonitoring()
        {
            while (true)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    if (_analytics.AverageProcessorLoad > _maxLoad)
                    {
                        HtmlPage.Window.Invoke("pauseEvent");
                    }
                    else
                    {
                        _toSendUnpause = true;
                    }

                    if (_toSendUnpause)
                    {
                        HtmlPage.Window.Invoke("unpauseEvent");
                        _toSendUnpause = false;
                    }
                    
//                    _cpuUsageBar.Dispatcher.BeginInvoke(delegate()
//                    {
                        _cpuUsageBar.Value = _analytics.AverageProcessorLoad;
//                    });

//                    _cpuUsageValue.Dispatcher.BeginInvoke(delegate()
//                    {
                        _cpuUsageValue.Text = _analytics.AverageProcessorLoad.ToString();
//                    });

                });
                Thread.Sleep(100);
            }
        }

        [ScriptableMember]
        public void SetMaxLoad(double newMaxLoad)
        {
            _maxLoad = newMaxLoad;
            maxUsage_value.Text = _maxLoad.ToString();
        }

    }
}
